package com.shaomengjie.meetingroom;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.shaomengjie.meetingroom.net.RetrofitHelper;
import com.shaomengjie.meetingroom.net.ServerApi;
import com.shaomengjie.meetingroom.utils.PrefsAccessor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static android.R.attr.button;
import static android.R.attr.multiArch;

public class LoginActivity extends AppCompatActivity {


    public static final String LOGIN = "LOGIN";
    public static final String REGISTER = "REGISTER";
    private String username;
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initRegisterView();
        initLoginView();
        setOnclick();
        initData();
    }

    private void initData() {
        String account = PrefsAccessor.getInstance(getApplicationContext()).getString("username");
        String password = PrefsAccessor.getInstance(getApplicationContext()).getString("password");
        if (!TextUtils.isEmpty(account)){
            mUserName.setText(account);
            mPassWord.setText(password);
        }

    }

    private void setOnclick() {
        mRelativeLayoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideKeyboard();
                if (!flag) {
                    setEnterAnimation(REGISTER);
                    startButtonAnimationLeft(mRelativeLayoutButton,0);
                    mPassWord.setVisibility(View.GONE);
                    mUserName.setVisibility(View.GONE);
                    mSure.setClickable(false);
                } else {
                    setEnterAnimation(LOGIN);
                    startButtonAnimationRight(mRelativeLayoutButton);
                    mPassWord.setVisibility(View.VISIBLE);
                    mUserName.setVisibility(View.VISIBLE);
                    mSure.setClickable(true);
                }
                flag = !flag;
            }
        });
        mSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
                loginSuccess();
            }
        });
        mPassWord.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    setUpAnimation(mUpRelativeLayout);
                }
            }
        });
    }

    /**
     * 登陆成功
     */
    private void loginSuccess() {
        Log.e("TAG",">>>>"+username+","+password);
        PrefsAccessor.getInstance(getApplicationContext()).saveString("username", username);
        PrefsAccessor.getInstance(getApplicationContext()).saveString("password", password);
    }

    /**
     * 登陆合法性验证
     */
    private void attemptLogin() {
        mUserName.setError(null);
        mPassWord.setError(null);
        username = mUserName.getText().toString().trim();
        password = mPassWord.getText().toString().trim();
        boolean cancel = false;
        View focusView = null;
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPassWord.setError(getString(R.string.error_invalid_password));
            focusView = mPassWord;
            cancel = true;
        }
        if (TextUtils.isEmpty(password)){
            mPassWord.setError(getString(R.string.error_invalid_password));
            focusView = mPassWord;
            cancel = true;
        }
        if (TextUtils.isEmpty(username)) {
            mUserName.setError(getString(R.string.error_field_required));
            focusView = mUserName;
            cancel = true;
        } else if (!isEmailValid(username)) {
            mUserName.setError(getString(R.string.error_invalid_email));
            focusView = mUserName;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {

            GoLogion(username,password);
        }

    }

    private void GoLogion(String username,String password) {
        Map<String,String> map = new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        ServerApi client = RetrofitHelper.getClient();
        Call<ResponseBody> call = client.login(map);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    System.out.println(">>>>"+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(LoginActivity.this,MainActivity2.class);
                startActivity(intent);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

    }

    private boolean isEmailValid(String email) {
        return true;
    }

    private boolean isPasswordValid(String password) {
        return password.length() > 4;
    }


    private void setEnterAnimation(String temp) {
        if (temp.equals(LOGIN)){
            mRelativeLayoutRegister.setVisibility(View.INVISIBLE);
            int left = mRelativeLayoutLogin.getLeft();
            int top = mRelativeLayoutLogin.getTop();
            startAnimation(mRelativeLayoutLogin,left,top,0);
        }else if (temp.equals(REGISTER)){
            mRelativeLayoutRegister.setVisibility(View.VISIBLE);
            int x = (mRelativeLayoutButton.getLeft() + mRelativeLayoutButton.getRight()) / 2;
            int y = (mRelativeLayoutButton.getTop() + mRelativeLayoutButton.getBottom()) / 2;
            float v = (float) mRelativeLayoutButton.getWidth() / 2;
            startAnimation(mRelativeLayoutRegister,x,y,v);
        }

    }

    /**
     * 按钮进入动画
     * @param temp
     * @param delay
     */
    private void startButtonAnimationLeft(RelativeLayout temp, int delay) {
        float curTranslationX = temp.getTranslationY();
        temp.setBackground(null);
        ObjectAnimator animator = ObjectAnimator.ofFloat(temp, "translationX", curTranslationX, -100f);
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(temp, "rotation", 45f);
        animator1.setDuration(500);
        ObjectAnimator animator3 = ObjectAnimator.ofFloat(temp, "translationY", curTranslationX, 50f, 0f);
        animator3.setDuration(500);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(temp, "alpha", 0f, 1f);
        AnimatorSet set = new AnimatorSet();
        set.play(animator).with(animator1).with(animator2).with(animator3);
        animator.setDuration(500);
        animator.setStartDelay(delay);
        set.start();
    }

    /**
     * 按钮退出动画
     * @param temp
     */
    private void startButtonAnimationRight(final RelativeLayout temp) {
        float curTranslationX = temp.getTranslationY();
        ObjectAnimator animator = ObjectAnimator.ofFloat(temp, "translationX", 0);
        animator.setDuration(500);
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(temp, "rotation", -90f);
        animator1.setDuration(500);
        ObjectAnimator animator3 = ObjectAnimator.ofFloat(temp, "translationY", curTranslationX, 50f, 0f);
        animator3.setDuration(500);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(temp, "alpha", 1f, 0f, 1f);
        animator2.setDuration(500);
        animator2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                Log.e("TAG","valueAnimator"+valueAnimator.getAnimatedValue());
                if ((float) valueAnimator.getAnimatedValue() < 0.2f) {
                    temp.setBackgroundResource(R.drawable.floating_button);
                }
            }
        });

        AnimatorSet set = new AnimatorSet();
        set.play(animator1).with(animator3).with(animator).with(animator2);
        set.start();

    }

    /**
     * 过渡动画
     * @param mRelativeLayoutRegister
     * @param x
     * @param y
     * @param v
     */
    private void startAnimation(RelativeLayout mRelativeLayoutRegister, int x, int y, float v) {
        final float finalRadius = (float) Math.hypot(mRelativeLayoutRegister.getWidth(), mRelativeLayoutRegister.getHeight());
        Animator anim = ViewAnimationUtils.createCircularReveal(
                mRelativeLayoutRegister, x, y, v,
                finalRadius);
        anim.setDuration(500);
        anim.setInterpolator(new AccelerateDecelerateInterpolator());
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                Log.e("---", "start anim");
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                Log.e("---", "end anim");
                //show views
            }
        });
        anim.start();

    }


    private boolean flag = false;
    private RelativeLayout mRelativeLayoutButton;
    private RelativeLayout mRelativeLayoutRegister;
    private RelativeLayout mRelativeLayoutLogin;
    private RelativeLayout mUpRelativeLayout;

    /**
     * 初始化变化的布局
     */
    private void initView() {
        mRelativeLayoutButton = (RelativeLayout) findViewById(R.id.floationgActionButton);
        mRelativeLayoutRegister = (RelativeLayout) findViewById(R.id.register);
        mRelativeLayoutLogin = (RelativeLayout) findViewById(R.id.login_rl);
        mUpRelativeLayout = (RelativeLayout) findViewById(R.id.up_RelativeLayout);
    }
    private EditText editText;

    /**
     * 初始化注册布局
     */
    private void initRegisterView() {
        editText = (EditText) findViewById(R.id.name);

    }

    private AutoCompleteTextView mUserName;
    private EditText mPassWord;
    private Button mSure;
    private LinearLayout linearLayout;
    /**
     * 初始化登录页面布局
     */
    private void initLoginView() {
        mUserName = (AutoCompleteTextView) findViewById(R.id.email);
        mPassWord = (EditText) findViewById(R.id.password);
        mSure = (Button) findViewById(R.id.email_sign_in_button);
        linearLayout = (LinearLayout) findViewById(R.id.email_login_form);

    }

    /**
     * 隐藏键盘
     */
    private void hideKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
                    hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 设置上升动画
     * @param relativeLayout
     */
    private void setUpAnimation(RelativeLayout relativeLayout) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(relativeLayout, "translationY", -200f);
        animator.setDuration(500);
        animator.start();
    }
}
